<template>
  <t-dialog v-model:visible="visible" attach="body" header="选择项目" width="70%">
    <div class="container">
      <t-space class="left" direction="vertical">
        <!-- 公司 -->
        <t-select
          v-model:value="companyId"
          :options="companySimpleList"
          :keys="{ label: 'name', value: 'id' }"
          label="归属公司："
          filterable
          @change="handleChangeCompany"
        />
      
        <!-- 类目树 -->
        <t-tree
          :data="categoryTree"
          activable
          v-model:actived="actived"
          v-model:expanded="expanded"
          expand-on-click-node
          hover
          :keys="{ label: 'name', value: 'id' }"
          max-height="calc(100vh - 380px)"
          @click="handleClickCategoryTree"
        />
      </t-space>
      <!-- 项目 -->
      <div v-show="selectedId" class="right">
        <!-- 自定义搜索 -->
        <custom-search ref="customSearchRef" v-slot="{ params }" @submit="handleInitTable">
          <t-col :span="4">
            <t-form-item label="项目名称" name="name">
              <t-input v-model:value="params.name" clearable placeholder="" />
            </t-form-item>
          </t-col>
        </custom-search>
        <custom-table
          ref="customTableRef"
          row-key="id"
          :columns="columns"
          :api="programmeCRUD.page"
          column-controller-key="ProgrammeList"
          :selected-row-keys="selectedRowKeys"
          @select-change="handleSelectChange"
          :on-before-set-data="handleTableSetData"
        >   
          <template #fileUrl="{ row }">
            <image-viewer v-if="row.fileUrl" :images="[row.fileUrl]" width="80px" height="80px" />
          </template>  
          <template #unit="{ row }">
            {{ dictionaryStore.analysis('unit', row.unit) }}
          </template>
          <template #profitMarginTotal="{ row }">
            {{ row.priceTotal!=0.00||0?`${((row.priceTotal-row.costPriceTotal)/row.priceTotal*100).toFixed(2)}%`:'' }}
          </template>
        </custom-table>
      </div>
      <t-empty v-show="!selectedId" class="right" title="请先选择类目" style="margin-top: 250px" />
    </div>
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <t-button theme="warning" @click="handleReset">重置</t-button>
      <t-button :loading="loadingSubmit" @click="handleSelectedIds">保存</t-button>
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import { laborCostsCRUD, budgetLaborCostsCRUD } from '@/api/budget/labor-costs';
import { programmeCRUD, programmeNameCRUD, updateQuotation } from '@/api/budget/programme';
import { getCompanyList } from '@/api/system/dept';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ImageViewer from '@/components/image-viewer/index.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';

const dictionaryStore = useDictionaryStore();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  single: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['update:visible', 'save']);

const visible = ref(props.visible);
const companyId = ref();
const companySimpleList = ref([]);
const categoryList = ref([]);
const categoryTree = ref([]);
const selectedId = ref();
const actived = ref([]);
const expanded = ref([]);
const selectedRowKeys = ref([]);
const selectedRows = ref(null);
const loadingSubmit = ref(false);
const programme = ref({ });
// columns
const columns = computed<TableCol[]>(() =>[
  { colKey: 'row-select', type: props.single ? 'single' : 'multiple', width: 64, fixed: 'left' },
  { colKey: 'name', title: '项目名称' },
  { colKey: 'remark', 
    title: '材料及工艺说明', 
    width:160, 
    ellipsis: true,
  },
  { colKey: 'fileUrl', title: '图片/视频' },
  { colKey: 'unit', title: '单位' ,width:60},
  // { 
  //   colKey: 'costPrice', 
  //   title: '成本(元)',
  //   children: [
  //     {colKey:'costMainMaterials', title:'主材',width:75},
  //     {colKey:'costAssistantMaterials', title:'辅材',width:75},
  //     {colKey:'costArtificial', title:'人工',width:75},
  //   ]
  //  },
  { 
    colKey: 'price', 
    title: '售价(元)',
    children: [
      {colKey:'quotationMainMaterials', title:'主材',width:75},
      {colKey:'quotationAssistantMaterials', title:'辅材',width:75},
      {colKey:'quotationArtificial', title:'人工',width:75},
    ]
   },
  { 
    colKey: 'total', 
    title: '总计',
    children: [
      {colKey:'priceTotal', title:'售价(元)',width:85},
      // {colKey:'costPriceTotal', title:'成本价(元)',width:85},
      // {colKey:'profitMarginTotal', title:'利润率',width:85},
    ]
  },
  // { colKey: 'createTime', title: '创建时间', width: 180 },
]);
const handleGetCompanySimpleList = async () => {
  return getCompanyList().then((data) => {
    companySimpleList.value = data;
    companyId.value = data[0].id;
  });
};

const handleGetCategory = () => {
 
  const params = {
    companyId: companyId.value,
    pageSize: -1,
  };
  programmeNameCRUD.page(params).then((data) => {
    categoryList.value = data.list;
    categoryTree.value = listToTree(data.list);
  });
  
};
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');


const handleSelectChange = (keys: any[], rows: any[]) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
};

const handleInitTable = () => {
  const params = {
    ...customSearchRef.value.params,
    companyId: companyId.value,
    budgetProjectId: selectedId.value,
  };
  customTableRef.value.initTable(params);
};
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  data.list.forEach((row:any)=> {
    row.projectId = row.id
    if(!row.quotationMainMaterials) row.quotationMainMaterials=0.00
    if(!row.quotationAssistantMaterials) row.quotationAssistantMaterials=0.00
    if(!row.quotationArtificial) row.quotationArtificial=0.00
    row.priceTotal = (row.quotationMainMaterials+row.quotationArtificial+row.quotationAssistantMaterials).toFixed(2)
    row.costPriceTotal = (row.costMainMaterials+row.costAssistantMaterials+row.costArtificial).toFixed(2)
  })
  return data

};
const handleClickCategoryTree = ({ node }: { node: TreeNodeModel }) => {
  if (node.data.parentId) {
    selectedId.value = node.value;
    handleInitTable();
  }
  
};

const handleChangeCompany = () => {
  handleReset()
  handleGetCategory();
};

const handleReset = () => {
  selectedRowKeys.value = [];
  selectedRows.value = null;
  customSearchRef.value.reset(); // 重置搜索条件
  selectedId.value = null;
  actived.value = []
  expanded.value = []
  customTableRef.value.data = [];
};

const handleSelectedIds = () => {
  if (selectedRows.value.selectedRowData.length === 0) {
    MessagePlugin.warning('请先选择数据');
    return;
  }

  const selectedData = selectedRows.value.selectedRowData.map((row: any) => {
    const { id, ...rest } = row; // 使用解构赋值将 `id` 从 `row` 中提取出来，剩下的属性放在 `rest` 中
    return {
      ...rest, // 展开 `rest`，包含除了 `id` 之外的所有属性
      projectName: row.name,
      unitPrice: row.priceTotal,
      projectId: row.id, // 将 `row.id` 赋值给 `projectId`
      materialsId: row.id,
    };
  });

  emits('save', selectedData);
  visible.value = false;
};

watch(
  () => props.visible,
  async (newVal) => {
    visible.value = newVal;
    if(newVal==true) {
      await handleGetCompanySimpleList();
      handleGetCategory();
      handleReset();
    }
  }
);

watch(visible, (newVal) => {
  emits('update:visible', newVal);
});

</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;

  @leftWidth: 300px;

  .left {
    width: @leftWidth;
  }

  .right {
    width: calc(100% - @leftWidth);
  }
}
</style>